/*
 * SPI_slave_receive.c
 *
 * Created: 11.01.2014 14:43:46
 *  Author: Max
 */ 


#define F_CPU         16000000L

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdint.h>
#include "UART_routines.h" //uart csedit

void uart0_init(void)
{
	UCSRB = 0x00; //disable while setting baud rate
	UCSRA = 0x00;
	UCSRC = (1 << URSEL) | 0x06;
	//	UBRRL = 0x33; //set baud rate lo orig.: 19
	//	UBRRL = 0x08; //set baud rate 57600
	UBRRL = 0x19; //set baud rate 19200
	UBRRH = 0x00; //set baud rate hi
	UCSRB = 0x18;
}


void SPI_SlaveInit(void)
{
	/* Set MISO output, all others input */
//	DDRB = (1<<4);	// Atmega 8, 328
	DDRB = (1<<6);	// Atmega 32
	/* Enable SPI */
	SPCR = (1<<SPE);
}
char SPI_SlaveReceive(void)
{
	/* Wait for reception complete */
	while(!(SPSR & (1<<SPIF)))
	;
	/* Return data register */
	return SPDR;
}

int main(void)
{
	char back;
	uart0_init();
	cli();
	SPI_SlaveInit();
	sei();
 	DDRB |= (1<<0);
	 
	 transmitByte(222);
	 	TX_NEWLINE;
		 transmitByte(222);
		 TX_NEWLINE;
		 transmitByte(222);
		 TX_NEWLINE;
		 transmitByte(222);
		 TX_NEWLINE;
	
	while(1)
	{
		back=SPI_SlaveReceive();
// 		for (int i=0; i<back;i++)
// 		{
// 			PORTB |= (1<<0);
// 			_delay_ms(20);
// 			PORTB &= ~(1<<0);
// 			_delay_ms(20);
// 		}
transmitByte(back);
TX_NEWLINE;
// 		if (back==3)
// 		{			
//  			PORTB |= (1<<0);
// 		}
// 		
// 		if (back==4)
// 		{
// 		 	PORTB &= ~(1<<0);
// 		}

	}
}